/**
 * create by young (young2f@outlook.com) on 2020/8/21
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Form, Popconfirm, Switch, Table} from 'antd';

import styles from '../index.less';
import {ModalView} from 'antd-extra';
import ViewTitle from '../../components/ViewTitle';
import ProductionElement from '../../components/ProductionElement';
import ModalRegisterUser from './modals/ModalRegisterUser';
import ComponentBase from '../../components/Base/ComponentBase';
import ModalEditUser from './modals/ModalEditUser';

const moment = require('moment');

@Form.create()
@connect(({global, user}) => ({...global, ...user}))
export default class Index extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'user/findUsers',
      payload: {resultKey: 'users'},
    });
  }

  onDataLoad = () => {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenant} = loginInfo;
    if (!tenant) return;
    const {tenantCode} = tenant;
    this.props.dispatch({
      type: 'user/findUsers',
      payload: {tenantCode, resultKey: 'users'},
    });
  };

  onEdit = (user) => {
    ModalView.open(ModalEditUser,
      {title: '编辑用户', width: '480px'},
      {
        user,
        update: true,
        editPassword: false,
        dispatch: this.props.dispatch,
        result: data => {
          this.props.dispatch(
            {type: 'user/updateUser', payload: data},
          ).then(res => {
            this.requestReturn(res);
            this.onDataLoad();
          });
        },
      },
    );
  };
  resetPassword = (user) => {
    this.props.dispatch({
      type: 'user/resetPassword',
      payload: {...user},
    }).then(res => {
      this.requestReturn(res);
      this.onDataLoad();
    });
  };
  delete = (record) => {
    const {userCode} = record;
    this.props.dispatch({
      type: 'user/deleteUser',
      payload: {userCode},
    }).then(res => {
      this.requestReturn(res);
      this.onDataLoad();
    });
  };

  create = () => {
    ModalView.open(ModalRegisterUser,
      {title: '注册用户', width: '480px'},
      {
        user: this.getLoginInfo(),
        update: false,
        dispatch: this.props.dispatch,
        result: data => {
          data.userType = 'user';
          this.props.dispatch(
            {type: 'user/register', payload: data},
          ).then(res => {
            this.requestReturn(res);
            this.onDataLoad();
          });
        },
      },
    );
  };

  columns = () => {
    const temp = [
      {
        title: '用户名', dataIndex: 'user',
        render: (value, record) => {

          const {userCode, username} = record;
          return (
            <ProductionElement code={userCode} name={username}></ProductionElement>
          );
        },
      },
      {title: '员工姓名', dataIndex: 'nickname', width: 150},
      {
        title: '角色', dataIndex: 'roleName', width: 250,
      },
      {title: '租户', dataIndex: 'tenantName', width: 250},
      {
        title: '管理员', dataIndex: 'isAdmin', width: 100, render: value => {
          return (<Switch checkedChildren="是" unCheckedChildren="否" checked={value}></Switch>);
        },
      },
      {title: '创建者', dataIndex: 'createUsername', width: 150},
      {
        title: '创建时间', dataIndex: 'createdTs', width: 200, render: value => {
          return (<div>{moment(value).format('YYYY-MM-DD HH:mm:ss')}</div>);
        },
      },
      {
        title: '操作', dataIndex: 'opt', width: 220,
        render: (value, record) => {
          const user = this.getLoginInfo();
          const {isAdmin, username} = record;
          return (
            <span>
              {<a style={{marginRight: '6px'}} onClick={() => this.onEdit(record)}>编辑</a>}

              {user.username !== username && <Popconfirm
                title="确认重置密码"
                onConfirm={() => this.resetPassword(record)}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>重置密码</a>
              </Popconfirm>
              }
              {!isAdmin && <Popconfirm
                title="确认删除"
                onConfirm={this.delete.bind(this, record)}
                okText="是"
                cancelText="否"
              >
                <a>删除</a>
              </Popconfirm>
              }
            </span>
          );
        },
      },
    ];
    return temp;
  };

  render() {
    const {users} = this.props;
    const loginInfo = wStore.getStore('loginInfo');
    let isSu = loginInfo.userType === 'su' ? true : false;
    return (<Form className={styles.content}>
      <ViewTitle
        title={'员工列表'}
        actions={[
          !isSu && <Button type={'primary'} onClick={this.create.bind(this)}>注册用户</Button>,
        ]}
      >
      </ViewTitle>
      <Table
        className={styles.antTable}
        bordered={true}
        columns={this.columns()}
        dataSource={users}
        // scroll={{ x: true }}
        pagination={true}
      >
      </Table>
    </Form>);
  }
}
